package com.xj.api.bussiness.deviceJpg.web;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xj.api.base.web.BaseController;
import com.xj.api.bussiness.deviceJpg.service.ITbDeviceJpgService;
import com.xj.common.base.common.bean.AbstractBean;
import com.xj.common.base.common.util.ImageUploadUtil;
import com.xj.common.bussiness.deviceJpg.entity.TbDeviceJpg;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * <p>
 *   前端控制器
 * </p>
 *
 * @author Mars
 * @since 2017-08-24
 */
@RestController
@RequestMapping("deviceJpg")
public class TbDeviceJpgController extends BaseController{
	
	@Autowired
	private ITbDeviceJpgService deviceJpgService;
	
	@GetMapping("/list.auth")
	@ApiOperation(value = " 获取图片列表", httpMethod = "GET", notes = "根据mac（mac）获取该用户的图片列表")
	public AbstractBean tbdevicejpgList(@RequestParam(required=false,defaultValue="0") Integer pageNum,@RequestParam(required=false,defaultValue="10") Integer pageSize,@RequestParam String mac){
		return json(deviceJpgService.selectMapsPage(new Page<TbDeviceJpg>(pageNum, pageSize), new EntityWrapper<TbDeviceJpg>().eq("device_mac", mac).orderBy("create_time", false)));
	}

	@GetMapping("/{mac}")
	@ApiOperation(value = "获取照片詳情", httpMethod = "GET", notes = "获取照片詳情")
	public AbstractBean getLastJpg(@PathVariable String mac){
		return json(deviceJpgService.selectOne(new EntityWrapper<TbDeviceJpg>().eq("device_mac", mac).orderBy("create_time", false).last("limit 1")));
	
	}
	
	
	@SuppressWarnings("unchecked")
	@GetMapping("/{mac}.auth")
	@ApiOperation(value = "获取单张詳情", httpMethod = "GET", notes = "根据设备mac（mac）和查询的开始时间（beginTime）和结束时间（endTime）获取图片詳情")
	public AbstractBean getJpg(@PathVariable String mac,@PathVariable Date beginTime ,@PathVariable Date endTime){
		return json(deviceJpgService.selectList((Condition.create().eq("device_mac", mac).between("create_time", beginTime, endTime))));
	}



	@RequestMapping(value = "/UploadFile",method = {RequestMethod.POST,RequestMethod.GET})
//@PostMapping("/UploadFile")
//@ApiOperation(value = "UploadFile", httpMethod = "POST")
	  public AbstractBean testUploadFile(HttpServletRequest req, MultipartHttpServletRequest multiReq) {
	    // 获取上传文件的路径(原文件的名字)
		System.out.println("你好啊  ");
	    String uploadFilePath = multiReq.getFile("jpg").getOriginalFilename();
	    System.out.println("uploadFlePath:" + uploadFilePath);
	    // 截取上传文件的文件名
	    String uploadFileName = uploadFilePath.substring( uploadFilePath.lastIndexOf('\\') + 1, uploadFilePath.indexOf('.'));
	    System.out.println("multiReq.getFile()" + uploadFileName);
	    // 截取上传文件的后缀
	    String uploadFileSuffix = uploadFilePath.substring( uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
	    System.out.println("uploadFileSuffix:" + uploadFileSuffix);
	    FileOutputStream fos = null;
	    FileInputStream fis = null;
	    try {
			//获取文件需要上传到的路径
//	        String path="/var/www/html/jpg";
	      String path="d://uploadFiles//";
	      System.out.println("path" + path);
	      fis = (FileInputStream) multiReq.getFile("jpg").getInputStream();
	      File file=new File(path);
	      if (file == null || !file.exists()) {
	    	  file.mkdirs();
          }
          //时间戳
	      long timestamp=System.currentTimeMillis();
	      fos = new FileOutputStream(file+"/" +uploadFileName +timestamp+ "." + uploadFileSuffix);
	      byte[] temp = new byte[1024];
	      int i = fis.read(temp);
	      while (i != -1){
	        fos.write(temp,0,temp.length);
	        fos.flush();
	        i = fis.read(temp);
	      }
	      TbDeviceJpg dj=new TbDeviceJpg();
	      String jpgPath="http://10.129.55.66/jpg/" +uploadFileName+ +timestamp+ "." + uploadFileSuffix;
	      //
	      dj.setMark(jpgPath!=null?jpgPath:""); //标记
	      dj.setDeviceMac(req.getParameter("mac")!=null?req.getParameter("mac"):""); //设备
	      dj.setBattery(Double.valueOf(req.getParameter("battery"))!=null?Double.valueOf(req.getParameter("battery")):0.0); //文件
	      dj.setLoadNumber(Double.valueOf(req.getParameter("loadNumber"))!=null?Double.valueOf(req.getParameter("loadNumber")):0.0); //装载次数
	      dj.setIsCharge(Integer.valueOf(req.getParameter("isCharge"))!=null?Integer.valueOf(req.getParameter("isCharge")):0);
	      dj.setAddress(req.getParameter("address")!=null?req.getParameter("address"):"");
	      
	      if(!deviceJpgService.insert(dj)){
	  		return error();
	  	    }
	  		return json(jpgPath);
	    } catch (IOException e) {
	      e.printStackTrace();
	    } finally {
	      if (fis != null) {
	        try {
	          fis.close();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	      }
	      if (fos != null) {
	        try {
	          fos.close();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	      }
	    }http://10.129.55.66/jpg/
		return null;
	  }
	
	
	@PostMapping("/save")
	@ApiOperation(value = "设备图片新增", httpMethod = "POST", notes = "图片新增")
	public AbstractBean add(HttpServletRequest req,TbDeviceJpg tbdevicejpg) throws IllegalStateException, IOException{
		if(tbdevicejpg.getDeviceMac().equals(null)&&tbdevicejpg.getDeviceMac().equals("")) {
		return fail("设备mac不能为空","-101");
		}
		ImageUploadUtil.upload(req, "d://uploadFiles//");
		tbdevicejpg.setMark("upload0");
		if(!deviceJpgService.insert(tbdevicejpg)){
		return error();
	    }
		return success();
	}


	
	
	
}
